package com.project.controller.web;

import com.alibaba.fastjson.JSON;
import com.project.entity.User;
import com.project.myBeans.ConfigParameters;
import com.project.myBeans.LoginInfo;
import com.project.myBeans.R;
import com.project.myBeans.ResponseBean;
import com.project.service.UserService;
import com.project.service.base.BaseService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by TAO on 2015/10/4.
 */
@Api(description="登录退出接口")
@Controller
public class LoginController extends BaseService {
    @Autowired
    UserService userService;

    @Autowired
    private ConfigParameters configParameters;

    @ApiOperation("用户登录")
    @RequestMapping(value = "/toLogin", method = RequestMethod.POST)
    @ResponseBody
    public R loginForm(@RequestBody LoginInfo loginInfo, HttpServletRequest request) {
        //设置fastjson禁止检测循环引用
        //JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.DisableCircularReferenceDetect.getMask();
        log.info("login>>>>>>>>>>>>>>");

        try {
            String msg, token;
            Long expirationTime;

            //用户是否登录
            Subject subject = SecurityUtils.getSubject(); // currentUser
            Session session = subject.getSession();
            User user = userService.findByUserName(loginInfo.getUsername());
            if (user == null) {
                return R.error("用户名或密码错误");
            }

            if (subject.isAuthenticated()){
                subject.logout();
            }

            //如果用户没有登录，跳转到登陆页面
            if (!subject.isAuthenticated()) {
                if (!userLogin(subject, request, loginInfo.getUsername(), loginInfo.getPassword())) {//登录失败时跳转到登陆页面,userLogin() in BaseService
                    return R.error("登录失败");
                }
            }

            //设置token
            DateTime dt = new DateTime();
            String key = configParameters.getJwtSecret();
            expirationTime = System.currentTimeMillis() + configParameters.getJwtExpire() * 1000; //毫秒

            token = Jwts.builder()         //创建token
                    .setIssuer(user.getId().toString())
                    .setExpiration(dt.plusSeconds(configParameters.getJwtExpire()).toDate())
                    .signWith(SignatureAlgorithm.HS512, key)
                    .compact();

            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id",user.getId());
            userInfo.put("username",user.getUsername());
            userInfo.put("usertype",user.getUsertype());
            userInfo.put("state",user.getState());

            return R.ok("登录成功").put("token",token).put("expire",expirationTime).put("user",userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("登录失败，请刷新重试");
        }
    }

    @ApiOperation("用户登录")
    @RequestMapping(value = "/toLogin2", method = RequestMethod.POST)
    @ResponseBody
    public R loginForm2(@RequestBody LoginInfo loginInfo, HttpServletRequest request) {

        ResponseBean responseBean = new ResponseBean();
        //设置fastjson禁止检测循环引用
        //JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.DisableCircularReferenceDetect.getMask();

        log.info("login>>>>>>>>>>>>>>");

        try {
            String msg, token;
            Long expirationTime;

            //用户是否登录
            Subject subject = SecurityUtils.getSubject(); // currentUser
            Session session = subject.getSession();
            User user = userService.findByUserName(loginInfo.getUsername());
            if (subject.isAuthenticated()){
//                subject.logout();
                return R.error("请勿重复登录,清除缓存");
            }
            if (user == null) {
                return R.error("用户名或密码错误");
            }

            //如果用户没有登录，跳转到登陆页面
            if (!subject.isAuthenticated()) {
                if (!userLogin(subject, request, loginInfo.getUsername(), loginInfo.getPassword())) {//登录失败时跳转到登陆页面,userLogin() in BaseService
                    return R.error("登录失败");
                }
            }

            //执行到此，表示用户名、密码是正确的
//            String username = request.getParameter("username");
            //获取用户菜单
//            session.setAttribute("currentUser", user);//session中设置当前用户

            //设置token
            DateTime dt = new DateTime();
            String key = configParameters.getJwtSecret();
            expirationTime = System.currentTimeMillis() + configParameters.getJwtExpire() * 1000; //毫秒

            token = Jwts.builder()         //创建token
                    .setIssuer(user.getId().toString())
                    .setExpiration(dt.plusSeconds(configParameters.getJwtExpire()).toDate())
                    .signWith(SignatureAlgorithm.HS512, key)
                    .compact();

            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id",user.getId());
            userInfo.put("username",user.getUsername());
            userInfo.put("usertype",user.getUsertype());
            userInfo.put("state",user.getState());

            return R.ok("登录成功").put("token",token).put("expire",expirationTime).put("user",userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("登录失败，请刷新重试");
        }


    }

    @ApiOperation("退出登录")
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public Object logout() {

        Subject subject = SecurityUtils.getSubject();

        subject.logout();

        return "login";
    }
}
